package com.heima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.Result;
import com.heima.domain.dto.SkuDto;
import com.heima.domain.po.Sku;
import com.heima.domain.vo.SkuVo;
import com.heima.mapper.SkuMapper;
import com.heima.service.SkuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 新增商品
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean addSku(SkuDto dto) {
        Sku sku = new Sku();
        BeanUtils.copyProperties(dto,sku);
        sku.setCreateTime(LocalDateTime.now());
        sku.setUpdateTime(LocalDateTime.now());
        try {
            skuMapper.insert(sku);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 分页查询商品
     *
     * @param pageIndex
     * @param pageSize
     * @param skuName
     * @return
     */
    @Override
    public Result getSkuByPage(Integer pageIndex, Integer pageSize, String skuName) {
        Page<SkuVo> page = new Page(pageIndex, pageSize);
        Page<SkuVo> sku = skuMapper.getSku(page, skuName);
        Result of = Result.of(sku);
        return of;
    }

    /**
     * 修改商品
     *
     * @param dto
     * @param skuId
     * @return
     */
    @Override
    public Boolean updateSku(SkuDto dto, Long skuId) {
        Sku sku = new Sku();
        BeanUtils.copyProperties(dto,sku);
        sku.setUpdateTime(LocalDateTime.now());
        boolean update = false;
        try {
            update = this.update(sku, lambdaQuery().getWrapper().eq(skuId != null, Sku::getSkuId, skuId));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return update;
    }
}
